const nodemailer = require("nodemailer");
// const result = require('./result.json')
const fs = require('fs')
const template = require('art-template')
const path = require('path');
const dayjs = require("dayjs");
const { host, user, pass } = require('./config.json')

template.defaults.imports.tail = function (data) {
  return data.shift().commit + data.shift().commit
}

// async..await is not allowed in global scope, must use a wrapper
async function send(to, subject, html) {
  // Generate test SMTP service account from ethereal.email
  // Only needed if you don't have a real mail account for testing
  // let testAccount = await nodemailer.createTestAccount();

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host,
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
      user,
      pass
      // user: testAccount.user, // generated ethereal user
      // pass: testAccount.pass, // generated ethereal password
    },
  });

  // send mail with defined transport object
  let info = await transporter.sendMail({
    from: '"李天成👻" <litiancheng@itcast.cn>', // sender address
    to, // list of receivers
    subject, // Subject line
    text: "", // plain text body
    html, // html body
  });

  console.log("Message sent: %s", info.messageId);
  // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

  // Preview only available when sending through an Ethereal account
  // console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
  // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

module.exports = {
  start(to) {
    const result = JSON.parse(fs.readFileSync('./result.json').toString('utf-8'))
    result.forEach(item => item.allCommits = item.data.reduce((sum, item) => sum += item.commit, 0))

    const noSubmit = result.filter(item => {
      return item.data.slice(0, 2).reduce((sum, item) => sum += item.commit, 0) === 0
    })

    const submited = result.filter(item => {
      return item.data.slice(0, 2).reduce((sum, item) => sum += item.commit, 0) > 0
    }).sort((a, b) => b.allCommits - a.allCommits)

    const html = template(path.join(__dirname, './result.html'), {
      submited,
      noSubmit
    })

    console.log(html)

    const nowDay = dayjs().format('YYYY-MM-DD')

    send(to, nowDay + " 94 期作业检查情况", html).catch(console.error);
  }
}